package com.leetcode;

/**
 * 52. N皇后 II
 *
 * @author fy
 * @date 2022/5/5 14:35
 */
public class Solution52 {

    private int res = 0;
    // 列占用记录
    private boolean[] col;
    // 左斜对角线占用记录
    private boolean[] leftTra;
    // 右斜对角线占用记录
    private boolean[] rightTra;

    public int totalNQueens(int n) {
        // 初始化列占用为false
        col = new boolean[n];
        for (int i = 0; i < n; i++) {
            col[i] = false;
        }
        // 初始化左斜对角线占用记录
        leftTra = new boolean[2 * n - 1];
        // 初始化右斜对角线占用记录
        rightTra = new boolean[2 * n - 1];
        for (int i = 0; i < 2 * n - 1; i++) {
            leftTra[i] = false;
            rightTra[i] = false;
        }
        putQ(n, 0);
        return this.res;
    }

    /**
     * 摆放n皇后的第row行(起始位置为0)的皇后, 前面行已经摆放的列位置放置在set中
     *
     * @param n
     * @param row
     */
    private void putQ(int n, int row) {

        if (row == n) {
            this.res++;
            return;
        }

        // 摆在第几列
        for (int i = 0; i < n; i++) {
            if (!col[i] && !leftTra[row + i] && !rightTra[row - i + n - 1]) {
                col[i] = true;
                leftTra[row + i] = true;
                rightTra[row - i + n - 1] = true;
                putQ(n, row + 1);
                rightTra[row - i + n - 1] = false;
                leftTra[row + i] = false;
                col[i] = false;
            }
        }
    }

}
